﻿using System.Collections.Generic;
using System.Text;
using Isaac.Joy.Cms.Module;

namespace Isaac.Joy.Cms.Repository.SqlClient
{
    class Repository : IRepository
    {
        public Product AddProduct(Product product)
        {
            var sbSql = new StringBuilder();
            sbSql.AppendLine("INSERT INTO Product ");
            sbSql.AppendLine("( ");
            sbSql.AppendLine("  Name ");
            sbSql.AppendLine("  ,Price ");
            sbSql.AppendLine(") ");
            sbSql.AppendLine("VALUES");
            sbSql.AppendLine("( ");
            sbSql.AppendLine("  @Name ");
            sbSql.AppendLine("  ,@Price ");
            sbSql.AppendLine("); ");
            sbSql.AppendLine("SELECT @@Identity; ");

            var id = Database.Instence.ExecuteScalar<int>(sbSql.ToString(),
                new
                {
                    @Name = product.Name,
                    @Price = product.Price
                });
            if (id <= 0) return null;

            product.Id = id;
            return product;
        }

        public IEnumerable<Product> QueryAll()
        {
            var sbSql = new StringBuilder();
            sbSql.AppendLine("SELECT * FROM Product");
            return Database.Instence.Query<Product>(sbSql.ToString());
        }
    }
}
